package com.kawa.kemanage.service.impl;

import com.kawa.kemanage.entity.dto.NewsLikeDTO;
import com.kawa.kemanage.entity.NewsLikes;
import com.kawa.kemanage.mapper.DoLikeMapper;
import com.kawa.kemanage.service.DoLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class DoLikeServiceImpl implements DoLikeService {
    @Autowired
    private DoLikeMapper doLikeMapper;



    /**
     * 查询不同新闻点赞总数
     *
     * @param
     * @return
     */
    @Override
    public List<NewsLikes> queryAllLikesCount() {
        return doLikeMapper.queryAllNewsLikesCount();
    }


    /**
     * 根据新闻id查询点赞总数
     *
     * @param newsId 新闻id
     * @return
     */
    @Override
    public Long queryLikesCountByNewsId(int newsId) {
        return doLikeMapper.queryLikesCountByNewsId(newsId);
    }

    /**
     * 查询是否已经点赞
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<Integer> getUserLikedContentIds(int userId) {
        return doLikeMapper.getUserLikedContentIds(userId);
    }

    /**
     * 增加点赞
     *
     * @param userId 用户id
     * @param contentId 内容id
     * @return
     */
    @Override
    @Transactional
    public boolean addLike(int userId, int contentId) {
        try {
            // 检查是否已存在
            if (doLikeMapper.existsLike(userId, contentId)) {
                return true; // 已存在则直接返回成功
            }

            Date createTime = new Date();
            int rows = doLikeMapper.addLike(userId, contentId, createTime);
            return rows > 0;
        } catch (Exception e) {
            // 处理唯一约束冲突（幂等性）
            if (e.getMessage().contains("Duplicate entry")) {
                return true;
            }
            return false;
        }

    }

    /**
     * 取消点赞
     *
     * @param userId 用户id
     * @param contentId 内容id
     * @return
     */
    @Override
    @Transactional
    public boolean cancelLike(int userId, int contentId) {
        try {
            int rows = doLikeMapper.cancelLike(userId, contentId);
            return rows > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<NewsLikeDTO> getLikesForUserArticles(Integer userId) {
        return doLikeMapper.getLikesForUserArticles(userId);
    }


}
